require 'pictopus'

module Rack
  class Pictopus
    def initialize(app, output_path)
      @app = app
      @root = ::File.expand_path(output_path)
      raise ArgumentError, "#{output_path} is not a directory." unless ::File.directory?(@root)
    end
    
    def call(env)
      unless env["PATH_INFO"] =~ /.*\/images\/pictopus\/.*\/.*/
        return @app.call(env)
      end
      
      request = ::Rack::Request.new(env)
      kind, command = env["PATH_INFO"].match(/images\/pictopus\/(.*)\/(.*)/i)[1..-1]
      
      if ::File.exist?(@root + env["PATH_INFO"])
        return ::Rack::File.new(@root).call(env)
      end
      
      case kind
        when "gradient"
          opts = {
            :output_path => @root
          }
          opts[:start_color], opts[:end_color], opts[:orientation], opts[:size], opts[:format] = command.split('.')
          ::Pictopus::Gradient.new(opts).run!
          
          # Redirect to this URL since it will now be served.
          [301, {'Location' => request.url}, 'Redirecting to created image.']
      end
    end
  end
end